<template>
  <basic-container
    custom-content="border-2 flex-initial pt-4 px-0"
    filter-class="mt-0"
    page-title="添加域名"
    back
  >
    <el-scrollbar v-loading="loading" class="px-4">
      <domain-add-form
        :loading="loading"
        :form-state="formState"
        :has-table="rrsSwitch === 1"
        @submit="handleSubmit"
      >
        <template v-if="rrsSwitchCache === 1" #rrsSwitch>
          <basic-switch v-model="rrsSwitch" />
        </template>
      </domain-add-form>
      <add-domain-error-dialog
        v-model:visible="errorDialogVisible"
        :state="domainErrorState"
      />
    </el-scrollbar>
  </basic-container>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'

import DomainAddForm from './components/DomainAddForm.vue'
import AddDomainErrorDialog from './dialogs/AddDomainErrorDialog.vue'
import type { RrsItem } from './type'

const router = useRouter()
const formRef = ref<FormInstance>()
const route = useRoute()

const formState = reactive({
  domains: '',
  rrs: [] as RrsItem[]
})

const rrsSwitch = ref(2)
const rrsSwitchCache = ref(2)

const loading = ref(false)
const domains = computed(() => getTrimValue(formState.domains))

const errorDialogVisible = ref(false)
const domainErrorState = reactive({
  success_count: '',
  success_rr_count: '',
  domain_count: '',
  fail_domains: [] as string[]
})

async function handleSubmit() {
  await formRef.value?.validate()
  const userId = route.params.userId as string
  loading.value = true
  try {
    const rrs =
      rrsSwitch.value === 1
        ? formState.rrs
            .map(v => ({ ...v, name: v.name || '@' }))
            .filter(v => v.value)
        : void 0
    const res = await addBatchDomainApi({
      user_id: userId,
      names: domains.value,
      rrs
    })

    const successRrCount = +(res.success_rr_count ?? '0')
    const domainTotalCount = +(res.domain_count ?? '0')
    const rrsTotalCount = rrsSwitch.value === 1 ? rrs?.length ?? 0 : 0

    if (
      +res.fail_domains!.length > 0 ||
      domainTotalCount * rrsTotalCount !== successRrCount
    ) {
      domainErrorState.success_count = res.success_count ?? '0'
      domainErrorState.success_rr_count = res.success_rr_count ?? '0'
      domainErrorState.domain_count = res.domain_count ?? '0'
      domainErrorState.fail_domains = res.fail_domains ?? []

      errorDialogVisible.value = true
    } else {
      ToastUtils.success(
        `<div class="pb-1">添加成功</div>
        <div>共添加${res.success_count}条域名，${res.success_rr_count}条记录</div>`
      )
      setTimeout(() => {
        router.push({ name: 'ManagerUserDomain', params: { id: userId } })
      }, 1000)
    }
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  const userId = route.params.userId as string
  if (!userId) {
    ToastUtils.error('用户不存在')
    return
  }
  const domains = history.state.domains as string[]
  if (domains?.length) {
    formState.domains = domains.join('\n')
  }
  history.state.domains = null

  loading.value = true
  configInfoApi({ key: ['feature'] })
    .then(res => {
      const data = res.feature!
      rrsSwitch.value = data.domain_add_show_rrs_switch!
      rrsSwitchCache.value = rrsSwitch.value
      formState.rrs = data.default_rrs!
    })
    .finally(() => {
      loading.value = false
    })
})
</script>

<style lang="scss" scoped>
.el-switch {
  height: 22px;
}
</style>
